<template>
    <el-dialog v-model="editData.visible" :title="editData.title" center width="50%" top="10vh" :close-on-click-modal="false">
        <div class="dialog-content">
            <el-form :model="editData.form" label-width="auto" style="width:100%" ref="formRef" :rules="editData.rules">
                <el-row :gutter="50">
                    <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
                        <el-form-item label="红方用户" prop="userId">
                            <el-input v-model="editData.form.userId" placeholder="请输入用户ID" clearable/>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
                        <el-form-item label="蓝方用户" prop="opponentId">
                            <el-input v-model="editData.form.opponentId" placeholder="请输入对手ID" clearable/>
                        </el-form-item>
                    </el-col>


                    <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
                        <el-form-item label="比赛地点" prop="location">
                            <el-input v-model="editData.form.location" clearable placeholder="请输入比赛地点名称"/>
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
                        <el-form-item label="详细地址" prop="address">
                            <el-input v-model="editData.form.address" clearable placeholder="请输入比赛详情地址"/>
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
                        <el-form-item label="地理经度" prop="longitude">
                            <el-input v-model="editData.form.longitude" clearable placeholder="请输入比赛地址经纬度"/>
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
                        <el-form-item label="地理纬度" prop="latitude">
                            <el-input v-model="editData.form.latitude" clearable placeholder="请输入比赛地址经纬度"/>
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
                        <el-form-item label="比赛时间" prop="time">
                            <el-date-picker v-model="editData.form.time" type="datetime" placeholder="请选择比赛时间" clearable style="width:100%"/>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
                        <el-form-item label="确认状态" prop="status">
                            <el-switch v-model="editData.form.status" :active-value="1" :inactive-value="0"/>
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
                        <el-form-item label="比赛赛制" prop="ruleId">
                            <el-select v-model="editData.form.ruleId" placeholder="请选择" style="width:100%" @change="ruleIdChange">
                                <el-option v-for="item in pointsRuleSList" :key="item.id" :label="item.label" :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" v-if="editData.form.ruleId">
                        <el-form-item label="比赛记录" prop="status">
                            <el-table :data="editData.form.scoreList" style="width: 100%" border stripe>
                                <el-table-column type="index" label="序号" align="center" width="100"/>
                                <el-table-column prop="a" label="红方选手" align="center">
                                    <template #default="scope">
                                        <el-input-number v-model="scope.row.a"></el-input-number>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="b" label="蓝方选手" align="center">
                                    <template #default="scope">
                                        <el-input-number v-model="scope.row.b"></el-input-number>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                        <el-form-item label="比赛照片" prop="status">
                            <el-upload v-model:file-list="editData.form.images"
                                       action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
                                       list-type="picture-card"
                                       :on-remove="handleRemove">
                                <el-icon>
                                    <Plus/>
                                </el-icon>
                            </el-upload>
                        </el-form-item>
                    </el-col>

                </el-row>
            </el-form>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="editData.visible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">确定</el-button>
            </div>
        </template>
    </el-dialog>
</template>


<script setup>
import { nextTick, reactive, ref, useTemplateRef } from 'vue'
import pointsRuleSApi from '@/api/model/points-rule-s.js'
import matchRecordApi from '@/api/model/match-record.js'
import { ElMessage } from 'element-plus'

const emits = defineEmits(['update'])
defineExpose({ openDialog })
const formRef = useTemplateRef('formRef')
const editData = reactive({
    type: 'add',
    visible: false,
    form: {
        id: '',
        userId: '',
        opponentId: '',
        location: '',
        address: '',
        longitude: '',
        latitude: '',
        ruleId: '',
        scoreList: [],
        time: '',
        status: 1,
        images: [],
    },
    rules: {
        nickname: [
            { required: true, message: '请输入用户名称', trigger: 'blur' },
            { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
    }
})

/**
 * 赛制规则变化
 */
function ruleIdChange () {
    console.log(editData.form.ruleId)
    const item = pointsRuleSList.value.find(item => item.id === editData.form.ruleId)
    editData.form.scoreList = Array.from(new Array(Number(item.set))).map(() => {
        return {
            a: 0,
            b: 0
        }
    })
}

const handleRemove = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles)
}

/**
 * 打开弹框
 * @param type
 * @param item
 */
function openDialog (type, item) {
    editData.title = type === 'add' ? '新增比赛' : '编辑比赛'
    editData.visible = true
    editData.type = type
    editData.form.id = ''
    nextTick(() => {
        formRef.value.resetFields()
        if (type === 'update') {
            const {
                id,
                status,
                userId,
                opponentId,
                time,
                ruleId,
                scoreList,
                images,
                longitude,
                latitude,
                location,
                address
            } = item || {}
            editData.form.id = id
            editData.form.status = status
            editData.form.userId = userId
            editData.form.opponentId = opponentId
            editData.form.time = time
            editData.form.ruleId = ruleId
            editData.form.scoreList = scoreList
            editData.form.images = images
            editData.form.longitude = longitude
            editData.form.latitude = latitude
            editData.form.location = location
            editData.form.address = address
        }
    })
}

/**
 * 提交表单
 */
function submitForm () {
    formRef.value.validate(async valid => {
        if (!valid) return
        editData.type === 'add' ? addItem() : updateItem()
    })
}

/**
 *  新增操作
 */
async function addItem () {
    let scoreResult = { a: 0, b: 0 }
    editData.form.scoreList.forEach(item => {
        if (item.a > item.b) {
            scoreResult.a++
        } else {
            scoreResult.b++
        }
    })

    const { code, data = [] } = await matchRecordApi.add.post({
        userId: editData.form.userId,
        opponentId: editData.form.opponentId,
        time: editData.form.time,
        ruleId: editData.form.ruleId,
        scoreList: editData.form.scoreList,
        scoreResult: scoreResult,
        images: editData.form.images,
        longitude: editData.form.longitude,
        latitude: editData.form.latitude,
        location: editData.form.location,
        address: editData.form.address,
        status: editData.form.status,
    })
    if (code === 200) {
        ElMessage.success('新增成功')
        editData.visible = false
        emits('update')
    } else {
        ElMessage.error('新增失败')
    }
}

/**
 *  更新操作
 */
async function updateItem () {
    let scoreResult = { a: 0, b: 0 }
    editData.form.scoreList.forEach(item => {
        if (item.a > item.b) {
            scoreResult.a++
        } else {
            scoreResult.b++
        }
    })
    const { code, data = [] } = await matchRecordApi.update.post({
        id: editData.form.id,
        userId: editData.form.userId,
        opponentId: editData.form.opponentId,
        time: editData.form.time,
        ruleId: editData.form.ruleId,
        scoreList: editData.form.scoreList,
        scoreResult: scoreResult,
        images: editData.form.images,
        longitude: editData.form.longitude,
        latitude: editData.form.latitude,
        location: editData.form.location,
        address: editData.form.address,
        status: editData.form.status,
    })
    if (code === 200) {
        ElMessage.success('编辑成功')
        editData.visible = false
        emits('update')
    } else {
        ElMessage.error('编辑失败')
    }
}

/**
 *  获取赛制列表
 */
const pointsRuleSList = ref([])
const getPointsRuleSList = async () => {
    const { code, data } = await pointsRuleSApi.list.get()
    if (code === 200) {
        pointsRuleSList.value = data
    } else {
        pointsRuleSList.value = []
    }
}
getPointsRuleSList()

</script>

<style lang="less">

</style>